/* Examples/jerasure_07.cpp
 * James S. Plank

Jerasure - A C/C++ Library for a Variety of Reed-Solomon and RAID-6 Erasure Coding Techniques
Copright (C) 2007 James S. Plank

James S. Plank
Department of Electrical Engineering and Computer Science
University of Tennessee 
Knoxville, TN 37996
plank@cs.utk.edu
*/

/*
 * $Revision: 1.2 $
 * $Date: 2008/08/19 17:41:40 $
 */
    

/*
	revised by S. Simmerman
	2/25/08  

  Jerasure 2.0
  6/1/11

*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "jerasure-2.h"

#define talloc(type, num) (type *) malloc(sizeof(type)*(num))

void usage(char *s)
{
  fprintf(stderr, "usage: jerasure_07 k m w - Scheduled Cauchy Reed-Solomon coding example in GF(2^w).\n");
  fprintf(stderr, "       \n");
  fprintf(stderr, "       k+m must be <= 2^w.  It sets up a Cauchy distribution matrix and encodes\n");
  fprintf(stderr, "       k sets of w*%ld bytes. It uses bit-matrix scheduling, both smart and dumb.\n", sizeof(uint64_t));
  fprintf(stderr, "       It decodes using bit-matrix scheduling, then shows an example of\n");
  fprintf(stderr, "       using JER_Do_Scheduled_Operations().\n");
  fprintf(stderr, "       \n");
  fprintf(stderr, "This demonstrates: JER_BM_To_Schedule_Dumb()\n");
  fprintf(stderr, "                   JER_BM_To_Schedule_Dumb()\n");
  fprintf(stderr, "                   JER_Schedule_Encode()\n");
  fprintf(stderr, "                   JER_Schedule_Decode_Lazy()\n");
  fprintf(stderr, "                   JER_Do_Scheduled_Operations()\n");
  fprintf(stderr, "                   JER_Get_Stats()\n");
  if (s != NULL) fprintf(stderr, "%s\n", s);
  exit(1);
}

static void print_data_and_coding(JER_Slices * slices)
{
  int i, j, x, n, sp;
  uint64_t l;
  int k,m,w,psize;

  k = slices->K;
  m = slices->M;
  w = slices->W;
  psize = slices->PS;

  if(k > m) n = k;
  else n = m;
  //the coding column is placed sp spaces from the left
  //13 spaces are just for the labels and separators
  //2 spaces per byte so psize*2
  sp = psize*2 + 13;

  printf("%-*sCoding\n", sp, "Data");
  for(i = 0; i < n; i++) {
    for (j = 0; j < w; j++) {
      if(i < k) {
        if(j==0) printf("D%-2d p%-2d:", i,j);
        else printf("    p%-2d:", j);
        for(x = 0; x < psize; x +=sizeof(uint64_t)) {
          memcpy(&l, slices->ptrs[i]+j*psize+x, sizeof(uint64_t));
          printf(" %016lx", l);
        }
        printf("    ");
      }
      else printf("%*s", sp, "");
      if(i < m) {
        if(j==0) printf("C%-2d p%-2d:", i,j);
        else printf("    p%-2d:", j);
        for(x = 0; x < psize; x +=sizeof(uint64_t)) {
          memcpy(&l, slices->ptrs[i+k]+j*psize+x, sizeof(uint64_t));
          printf(" %016lx", l);
        }

      }
      printf("\n");
    }
  }

  printf("\n");
}

int main(int argc, char **argv)
{
  uint64_t l;
  int k, w, i, j, m;
  JER_Matrix * matrix;
  JER_Bitmatrix *bitmatrix;
  vector <unsigned char *> ptrs;
  JER_Schedule * dumb, *smart;
  vector <int> erasures;
  vector <int> erased;
  vector <double> stats;
  JER_Slices * slices;

  if (argc != 4) usage(NULL);
  if (sscanf(argv[1], "%d", &k) == 0 || k <= 0) usage((char*)"Bad k");
  if (sscanf(argv[2], "%d", &m) == 0 || m <= 0) usage((char*)"Bad m");
  if (sscanf(argv[3], "%d", &w) == 0 || w <= 0 || w > 32) usage((char *)"Bad m");
  if (w < 30 && (k+m) > (1 << w)) usage((char *)"k + m is too big");

  matrix = new JER_Matrix(m,k,w);

  for (i = 0; i < m; i++) {
    for (j = 0; j < k; j++) {
      matrix->Elts[i][j] = galois_single_divide(1, i ^ (m + j), w);
    }
  }
  
  //convert it to a bitmatrix
  bitmatrix = new JER_Bitmatrix(*matrix);

  printf("Last m rows of the Binary Distribution Matrix:\n\n");
  bitmatrix->Print();
  printf("\n");

  //create schedules
  dumb = JER_BM_To_Schedule_Dumb(bitmatrix);
  smart = JER_BM_To_Schedule_CSHR(bitmatrix);

  //setup slices
  slices = new JER_Slices;
  slices->ptrs.resize(k+m);
  slices->K = k;
  slices->M = m;
  slices->W = w;
  slices->PS = sizeof(uint64_t);
  slices->size = sizeof(uint64_t)*w;

  //put original data in slices
  srand48(0);
  for (i = 0; i < k; i++) {
    slices->ptrs[i] = talloc(unsigned char, sizeof(uint64_t)*w);
    for (j = 0; j < w; j++) {
      l = (uint64_t)lrand48();
      l <<= 8*4;
      l += (uint64_t)lrand48();
      memcpy(slices->ptrs[i]+j*sizeof(uint64_t), &l, sizeof(uint64_t));
    }
  }

  //allocate space for the slices of coding data
  for (i = k; i < k+m; i++) {
    slices->ptrs[i] = talloc(unsigned char, sizeof(uint64_t)*w);
    //initialize them to 0
    bzero(slices->ptrs[i],sizeof(uint64_t)*w);
  }

  //encode with schedules
  JER_Schedule_Encode(slices, dumb);
  stats.resize(3,0);
  JER_Get_Stats(stats);
  printf("Dumb Encoding Complete: - %.0lf XOR'd bytes\n\n", stats[0]);
  print_data_and_coding(slices);

  JER_Schedule_Encode(slices,smart);
  JER_Get_Stats(stats);
  printf("Smart Encoding Complete: - %.0lf XOR'd bytes\n\n", stats[0]);
  print_data_and_coding(slices);

  //erase devices
  erasures.resize(m);
  erased.resize(m+k,0);

  for (i = 0; i < m; ) {
    erasures[i] = lrand48()%(k+m);
    if (erased[erasures[i]] == 0) {
      erased[erasures[i]] = 1;
      bzero(slices->ptrs[erasures[i]],sizeof(uint64_t)*w);
      i++;
    }
  }
  printf("Erased %d random devices:\n\n", m);
  print_data_and_coding(slices);

  //decode lazy (smart)
  JER_Schedule_Decode_Lazy(slices, bitmatrix, erasures, 1);
  JER_Get_Stats(stats);
  printf("State of the system after decoding: %.0lf XOR'd bytes\n\n", stats[0]);
  print_data_and_coding(slices);

  //prepare to Do_Scheduled_Operations
  ptrs.resize(k+m);
  for (i = 0; i < (k+m); i++) ptrs[i] = slices->ptrs[i];

  //clear all coding drives
  for (j = k; j < k+m; j++) bzero(slices->ptrs[j], sizeof(uint64_t)*w);
  JER_Do_Scheduled_Operations(ptrs, smart,slices->PS);
  printf("State of the system after deleting the coding devices and\n");
  printf("using jerasure_do_scheduled_operations(): %.0lf XOR'd bytes\n\n", stats[0]);
  print_data_and_coding(slices);

  delete matrix;
  delete slices;
  delete bitmatrix;
  delete dumb;
  delete smart;

  return 0;
}
